package com.crashcollection.util.file;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;

import com.crashcollection.util.ftp.UploadFileService;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.StatFs;

/**
 * 文件操作类
 * @author Zhongdaxia 2013年7月8日 16:25:29
 * 
 * API:
 * FileHelper fileHelper = new FileHelper(this);
 * 获取sd目录下所有avi和jpg
 * fileHelper.getFileList(fileHelper.getSdCardRootDir(),"*.avi");                                                  // 搜索sd卡所有avi
 * fileHelper.getFileList(fileHelper.getSdCardRootDir() + "YouBoxAdPlayer/download/","*.rmvb,*.flv,*.avi");        // 搜索 sdcard/YouBoxAdPlayer/download/ 目录下 所有rmvb/flv/avi
 * fileHelper.getFileList(fileHelper.getSdCardRootDir() + "YouBoxAdPlayer/download/","*.*");                       // 搜索 sdcard/YouBoxAdPlayer/download/ 目录下 所有文件
 * 
 * 删除文件
 * fileHelper.deleteFile(fileHelper.getSdCardRootDir() + "YouBoxAdPlayer/download/vr.avi");
 * 
 * 获取sd容量
 * long maxsize = fileHelper.getSdInfo(1);
 * 获取sd剩余可用空间
 * long freesize = fileHelper.getSdInfo(2);
 */

public class FileHelper {
	Context context;
	public FileHelper(Context context)
	{
		this.context = context;
	}

	/**
	 * 
	 * 获取指定位置的指定类型的文件
	 * @param path 文件夹路径
	 * @param type 文件类型    如.jpg;*.png;*.gif   [单条件][*.jpg]   [多条件][*.jpg,*.png,*.gif]   [显示所有][*]
	 * @param func       构造json的功能号                   null  默认不构造
	 * @param listType   构造json的list类型          null  默认不构造
	 * return func listType 不为null 自动json并发送
	 */
	public void getFileList(String path, String type , final String func , final String listType) {
		
		if(!isSdCardExist())
		{
			return;
		}
		
		new AsyncTask<String, String, String>() {
			
			ArrayList<FileInfoBean> list = new ArrayList<FileInfoBean>();

			// 执行完成之后
			@Override
			protected void onPostExecute(String result) {
				return;
			}
			
			//执行之前
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}
			
			//背景进程
			@Override
			protected String doInBackground(String... params) {
				// 搜索路径
				File scanPath = new File(params[0]);

				// 搜索类型
				String [] scanTypeArray = null;
				
				String scanType = params[1];
				
				if (scanType.indexOf(",") >= 0) {
						scanTypeArray = scanType.split(",");
				}
				
				if(null != scanTypeArray && scanTypeArray.length != 0)
				{
					for(int i = 0 ; i < scanTypeArray.length ; i ++)
					{
						scanTypeArray[i] = scanTypeArray[i].substring(scanTypeArray[i].lastIndexOf(".") + 1);
					}
				}
				else
				{
					scanTypeArray = new String[1];
					scanTypeArray[0] = scanType.substring(params[1].lastIndexOf(".") + 1);
				}
				
				scanSDCard(scanPath, scanTypeArray , list);
				
				// 获取到文件列表 - 执行文件上传
				UploadFileService.UpLoadFile(list);
				return null;
			}

		}.execute(path, type);
	}

	/**
	 * 
	 * @param file  
	 * @param ext
	 * @param list
	 */
	private void scanSDCard(File scanPath, String [] scanTypeArray, ArrayList<FileInfoBean> list) {
                if (scanPath.isDirectory()) {
                        File[] files = scanPath.listFiles();
                        if (files != null) {
                                for (int i = 0; i < files.length; i++) {
                                        File tmp = files[i];
                                        if (tmp.isFile()) {
                                                String fileName = tmp.getName();
                                                if (fileName.indexOf(".") >= 0) {
                                                	
                                                        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
                                                        
                                                        // *.* 全部
                                                        if(scanTypeArray[0].equals("*"))
                                                        {
                                                        	 FileInfoBean info = new FileInfoBean();
                                                             info.filename = fileName;
                                                             info.filesize = Long.toString(getFileSize(tmp));
                                                             info.playlenth = tmp.getAbsolutePath();
                                                             info.createtime = getFileCreateTime(tmp);
                                                             list.add(info);
                                                        }
                                                        else {
                                                        	 for(int j = 0 ; j < scanTypeArray.length ; j ++)
                                                             {
                                                             	 if (scanTypeArray[j] != null && scanTypeArray[j].equalsIgnoreCase(fileType)) {
                                                                      FileInfoBean info = new FileInfoBean();
                                                                      info.filename = fileName;
                                                                      info.filesize = Long.toString(getFileSize(tmp));
                                                                      info.playlenth = tmp.getAbsolutePath();
                                                                      info.createtime = getFileCreateTime(tmp);
                                                                      list.add(info);
                                                                  }
                                                             }
														}
                                                }
                                        } else
                                                scanSDCard(tmp, scanTypeArray, list);
                                }
                        }
                } else {
                        if (scanPath.isFile()) {
                                String fileName = scanPath.getName();
                                if (fileName.indexOf(".") >= 0) {
                                	
                                	 String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
                                	 
                                     // *.* 全部
                                     if(scanTypeArray[0].equals("*"))
                                     {
                                    	 FileInfoBean info = new FileInfoBean();
                                    	 info.filename = fileName;
                                         info.filesize = Long.toString(getFileSize(scanPath));
                                         info.playlenth = scanPath.getAbsolutePath();
                                         info.createtime = getFileCreateTime(scanPath);
                                     }
                                     else {
                                    	 for(int j = 0 ; j < scanTypeArray.length ; j ++)
                                         {
                                    		 if (scanTypeArray[j] != null && scanTypeArray[j].equalsIgnoreCase(fileType)) {
                                             	FileInfoBean info = new FileInfoBean();
                                           	    info.filename = fileName;
                                                info.filesize = Long.toString(getFileSize(scanPath));
                                                info.playlenth = scanPath.getAbsolutePath();
                                                info.createtime = getFileCreateTime(scanPath);
                                             }
                                         }
                                     }
                                }
                        }
                }
        }
	
	/**
	 * 获取文件大小
	 * @param file
	 * @return
	 */
	private long getFileSize(File  file)
	{
		if (file.exists()) {
			return file.length();
		} else {
			return -1;
		}
	}
	
	/**
	 * 获取文件最后修改时间
	 * @param file
	 * @return
	 */
	private String getFileCreateTime(File  file)
	{
		if(file.exists())
		{
			Date date=new Date(file.lastModified()); 
			return date.toGMTString();
		}
		return null;
	}
	
	public boolean isSdCardExist() {
		return Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
	}

	public String getSdCardRootDir() {
		return Environment.getExternalStorageDirectory().getPath() + "/";
	}

	/**
	 * 删除文件
	 * @param path
	 * @return
	 */
	public static void deleteFile(String path) {
		try {
			File file = new File(path);
			if(file.exists())
			{
				file.delete();
			}
		} catch (Exception ex) {
		}
	}

	/**
	 * 文件是否存在
	 * @param path
	 * @return
	 */
	public boolean isFileExist(String path) {
		try {
			File file = new File(path);
			return file.exists();
		} catch (Exception ex) {
		}

		return false;
	}
	
	/**
	 * 获取sd空间信息
	 * @param getType   [1]:[maxsize]   [2]:[freesize]
	 * @return          [-1]:[error gettype]  [-2]:[error get]    
	 */
	public long getSdInfo(int getType)
	{
		String state=Environment.getExternalStorageState();//获取SD卡状态
        if(state.equals(Environment.MEDIA_MOUNTED)){
            File sdFile=Environment.getExternalStorageDirectory();
            StatFs statfs=new StatFs(sdFile.getPath());
            long size=statfs.getBlockSize();//每个block的大小
            long total=statfs.getBlockCount();//总block的大小
            long available=statfs.getAvailableBlocks();//可用block的大小
            if(getType == 1)
            {
            	return total*size/1024/1024;
            }
            else if(getType == 2)
            {
            	return available*size/1024/1024;
            }
            else {
				return -1;
			}
        }
        return -2;
	}
	
}